package edu.nf.db.util.result;

import edu.nf.db.util.ResultSetHandler;
import edu.nf.db.util.RowProcessor;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Author lzp
 * @Date 2024-05-08
 * 查询单列的值
 */
public class ColumnHandler<T> implements ResultSetHandler<T> {

    //尽量用包装类因为 int 这些类型是有默认值的 而包装类型默认是 null

    /**
     * 列的下标
     */
    private Integer colunIndex;
    /**
     * 列名
     */
    private String colunName;

    public ColumnHandler(Integer colunIndex) {
        this.colunIndex = colunIndex;
    }

    public ColumnHandler(String colunName) {
        this.colunName = colunName;
    }

    @SuppressWarnings("unchecked")
    @Override
    public T handle(ResultSet rs) throws SQLException {
        if (rs.next()){
            if (this.colunIndex == null){
                return (T) RowProcessor.toValue(rs,colunName);
            }
            return (T) RowProcessor.toValue(rs,colunIndex);
        }
        return null;
    }
}
